import 'dart:io';

import 'package:ems_neutral_app/pages/Mine/Language/SilLocalizations/SilLocalizations.dart';
import 'package:ems_neutral_app/utils/color/ColorUtils.dart';
import 'package:ems_neutral_app/utils/eventBus/eventBus.dart';
import 'package:ems_neutral_app/utils/sputils/SpUtils.dart';
import 'package:ems_neutral_app/utils/string/StringConstant.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:sil_base_widget_package/sil_base_widget_package.dart';
import 'package:sil_utils_package/utils/device/DeviceUtils.dart';

import 'bloc/userbloc/user_bloc.dart';
import 'common/Method/CommonMethod.dart';
import 'common/module/WillPopScopeApp/WillPopScopeAppPage.dart';
import 'common/widgets/dialog/AgreeDialog.dart';
import 'config/AppInfo.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

import 'pages/Launch/LaunchAnimationPage.dart';
import 'pages/Launch/LaunchPage.dart';
import 'pages/Login/LoginGuidPage.dart';
import 'utils/permission/PermissionUtils.dart';
import 'utils/pushMessage/PushMessageUtils.dart';

void main() {
  // 监测网络变化
  // NetworkShareInstance();

  // 设置状态条，dart:io库不兼容web，这里做异常处理
  try {
    if (Platform.isAndroid) {
      SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(
          statusBarColor: Colors.transparent, //全局设置透明
          statusBarIconBrightness: Brightness.light);
      SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
    }
  } catch (e) {
    print('当前是web');
  }

  runApp(MultiBlocProvider(
      providers: [BlocProvider<UserBloc>(create: (context) => UserBloc())],
      child: MyApp()));
}

/**设置主导航栈的key */
GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();
/**用于监听生命周期 */
RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();

Widget homePage = Container();
int pageType = SHOW_VERSION_AGREE ? 0 : 2; // 0空页面；1协议弹窗页；2启动动画 3主页面

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    // 初始化toast
    SilToast().init(navigatorKey);
    // 强制竖屏
    DeviceUtils.deviceToPortrait();
    // 初始化轻量级缓存
    SpUtils.init(context: context);

    return MyHomePage(title: 'Flutter Demo Home Page');
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();

    if (SHOW_VERSION_AGREE) {
      //是否同意版本协议
      bus.on(StringConstant.SpUtilsInitFinished, (arg) async {
        String versionStr = APP_VERSION_AGREE;
        bool agree = await SpUtils.getBoolData(versionStr);
        if (agree == true) {
          pageType = 2;
          initThird();
        } else {
          pageType = 1;
        }
        setState(() {});
      });

      // 用户同意了版本协议
      bus.on(StringConstant.VersionProtocolAgree, (value) {
        pageType = 2;
        initThird();
        setState(() {});
      });
    } else {
      initThird();
    }

    // 启动动画结束了
    bus.on(StringConstant.LaunchAnimationFinished, (arg) {
      pageType = 3;
      setState(() {});
    });

    /// 用户登录状态发生改变
    bus.on(StringConstant.UserLoginInEvent, (arg) async {
      setState(() {});
    });
    bus.on(StringConstant.UserLoginOutEvent, (arg) async {
      setState(() {});
    });

    // app语言发生了变化
    bus.on(StringConstant.LanguageChange, (value) {
      setState(() {});
    });

    /// 用户添加了第一个电站，返回主页面
    bus.on(StringConstant.PowerStationsFirstAdded, (value) {
      setState(() {});
    });
  }

  /// 初始化第三方
  initThird() {
    // 初始化推送
    PushMessageUtils.setup();

    // 检查权限
    checkNotification();
  }

  // 通知权限
  checkNotification() async {
    bool value = await PermissionUtils.permission_notification();
    AppInfo.notificationPerm = value;
    // if (value) {
    // // 是否有推送消息，打开的app
    // if (AppInfo.launchAppGetNotification) {
    // AppInfo.launchAppGetNotification = false;
    // PushMessageUtils.launchAppNotification();
    // }
    // }
  }

  @override
  Widget build(BuildContext context) {
    return screenUtilInit();
  }

  /// 初始化屏幕适配插件
  screenUtilInit() {
    return NumUtils.initScreenUtilInit(
      designSize: Size(375, 812),
      builder: (context, build) {
        return RefreshConfiguration(
            footerTriggerDistance: 15,
            dragSpeedRatio: 0.91,
            headerBuilder: () => MaterialClassicHeader(),
            footerBuilder: () => ClassicFooter(),
            enableLoadingWhenNoData: false,
            enableRefreshVibrate: false,
            enableLoadMoreVibrate: false,
            shouldFooterFollowWhenNotFull: (state) {
              return false;
            },
            child: mainWidget(getCurStateWidget(pageType)));
      },
    );
  }

  /// 获取当前应该显示的视图
  getCurStateWidget(int pageType) {
    late Widget widget;
    switch (pageType) {
      case 1: // 协议弹窗页面
        widget = AgreeDialog();
        break;
      case 2: // 启动动画页面
        widget = LaunchAnimationPage();
        break;
      case 3: // 主页面
        if (UserBlocTool.isLogin() == true) {
          widget = LaunchPage();
        } else {
          widget = LoginGuidPage();
        }
        break;
      default: // 空页面
        {
          widget = Container(color: ColorUtils.color_bg);
        }
    }
    // widget = LaunchPage();

    // /**设置主导航栈的key */
    navigatorKey = new GlobalKey<NavigatorState>();
    /**用于监听生命周期 */
    routeObserver = RouteObserver<PageRoute>();

    return widget;
  }

  /// 主页面
  mainWidget(Widget home) {
    return MaterialApp(
        debugShowCheckedModeBanner: false, // 去掉debug标识
        localizationsDelegates: [
          SilLocalizations.delegate,
          RefreshLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalMaterialLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
        ],
        supportedLocales: SilLocalizations.supportedLocales, // 使用自己的语言列表
        locale: SilLocalizations.curSupportedLocale(),
        localeResolutionCallback: SilLocalizations.localeResolutionCallback,
        navigatorObservers: [routeObserver],
        navigatorKey: navigatorKey,
        title: APP_NAME,
        theme: ThemeData(
          primarySwatch: Colors.blue,
          primaryColor: ColorUtils.color_theme,

          /// 去掉水波纹效果，将水波纹颜色和点击后的背景色设置一致，水波纹效果就不显示了
          highlightColor: ColorUtils.color_bg,
          splashColor: ColorUtils.color_bg,
        ),
        builder: (context, child) {
          // 设置设计尺寸
          SilBaseWidgetSetting.init(designSize: Size(375, 812));

          // 配置弹窗的样式
          SilAlertDialogInfo().mode = AlertDialogMode.Dark;
          SilAlertDialogInfo().horizontalMargin = 48.w;
          SilAlertDialogInfo().buttonHeight = 45.w;
          SilAlertDialogInfo().backgroundColor = ColorUtils.color_bottom_sheet;
          SilAlertDialogInfo().confrimButtonStyle =
              TextStyle(color: ColorUtils.color_theme, fontSize: 17.sp);

          // 输入文本设置
          SilTextFieldDataManager.closeImg =
              'imgs/common/system_icon_delete_hery.png';
          SilTextFieldDataManager.closeEyeImg =
              'imgs/login/icon_land_password_nor@3x.png';
          SilTextFieldDataManager.openEyeImg =
              'imgs/login/icon_land_password_ser@3x.png';
          SilTextFieldDataManager.inputDecoration = InputDecoration.collapsed(
            hintText: "请输入内容",
            hintStyle: TextStyle(
              color: ColorUtils.color_font_minor,
              fontSize: 14,
            ),
          );
          SilTextFieldDataManager.textStyle =
              TextStyle(color: ColorUtils.color_font_main, fontSize: 14.sp);

          return SilToast().botToastBuilder(
              context,
              MediaQuery(
                  child: GestureDetector(
                    child: child ?? Container(),
                    onTap: () {
                      globalTextFieldDismiss(context);
                    },
                  ),
                  data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0)));
        },
        home: WillPopScopeAppPage(child: home),
        routes: {});
  }
}
